import React, { useState, useEffect } from 'react';
import { Table, Form, Input, Button, message, Space, Modal } from 'antd';
import { ExclamationCircleFilled } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { AddShelfManage } from './AddShelfManage';
import { EditShelfManage } from './EditShelfManage';

// 定义数据类型
interface ShelfItem {
  id: number;
  shelfName: string;
  shelfNumber: string;
  boxNumber: string;
  skuType: number;
  skuNum: number;
}

// 定义查询参数类型
interface QueryParams {
  shelfName?: string;
  shelfNumber?: string;
}

const ShelfManageQuery: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<ShelfItem[]>([]);
  const [total, setTotal] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [isAddModalOpen, setIsAddModalOpen] = useState(false);
  const [isEditModalOpen, setIsEditModalOpen] = useState(false);
  const [currentShelf, setCurrentShelf] = useState<ShelfItem | null>(null);

  // 删除货架
  const handleDelete = async (id: number) => {
    if (!window.confirm('确定要删除这个货架吗？')) {
      return;
    }

    try {
      const response = await fetch(`http://localhost:5233/api/ShelfManage/DelShelfManageModel?Id=${id}`, {
        method: 'DELETE',
      });

      const result = await response.json();
      
      if (result.code === 200) {
        message.success(result.message || '删除成功');
        fetchData({}); // 刷新列表
      } else {
        throw new Error(result.message || '删除失败');
      }
    } catch (error) {
      message.error('删除失败，请重试');
    }
  };

  // 打开编辑弹窗
  const handleEdit = (record: ShelfItem) => {
    setCurrentShelf(record);
    setIsEditModalOpen(true);
  };

  // 表格列定义
  const columns: ColumnsType<ShelfItem> = [
    {
      title: '序号',
      dataIndex: 'id',
      key: 'id',
      width: 100,
      align: 'center',
    },
    {
      title: '货架名称',
      dataIndex: 'shelfName',
      key: 'shelfName',
      width: 200,
      ellipsis: true,
    },
    {
      title: '货架编号',
      dataIndex: 'shelfNumber',
      key: 'shelfNumber',
      width: 200,
      ellipsis: true,
    },
    {
      title: '箱子数量',
      dataIndex: 'boxNumber',
      key: 'boxNumber',
      width: 150,
      align: 'center',
    },
    {
      title: 'SKU种类',
      dataIndex: 'skuType',
      key: 'skuType',
      width: 150,
      align: 'center',
    },
    {
      title: 'SKU数量',
      dataIndex: 'skuNum',
      key: 'skuNum',
      width: 150,
      align: 'center',
    },
    {
      title: '操作',
      key: 'operation',
      fixed: 'right',
      width: 200,
      align: 'center',
      render: (_, record) => (
        <Space size="small">
          <Button type="primary" size="small" onClick={() => message.info('查看明细功能待实现')}>
            货架明细
          </Button>
          <Button type="primary" size="small" onClick={() => handleEdit(record)}>
            修改
          </Button>
          <Button 
            type="primary" 
            danger 
            size="small" 
            onClick={() => handleDelete(record.id)}
          >
            删除
          </Button>
        </Space>
      ),
    }
  ];

  // 查询数据
  const fetchData = async (params: QueryParams) => {
    try {
      setLoading(true);
      const queryParams = {
        ...params,
        pageindex: currentPage,
        pagepage: pageSize
      };
      const queryString = new URLSearchParams(queryParams as any).toString();
      const response = await fetch(`http://localhost:5233/api/ShelfManage/ShelfManageModelQuery?${queryString}`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
      });

      const result = await response.json();
      if (result.code === 200) {
        setData(Array.isArray(result.data) ? result.data : (result.data?.pageData || []));
        setTotal(result.data?.totalCount || 0);
      } else {
        message.error(result.message || '查询失败');
      }
    } catch (error) {
      message.error('查询出错：' + error);
      setData([]);
      setTotal(0);
    } finally {
      setLoading(false);
    }
  };

  // 处理查询
  const handleSearch = async () => {
    const values = await form.validateFields();
    setCurrentPage(1); // 重置到第一页
    fetchData(values);
  };

  // 重置表单
  const handleReset = () => {
    form.resetFields();
    setCurrentPage(1); // 重置到第一页
    setPageSize(10); // 重置每页条数
    fetchData({});
  };

  // 组件加载时获取数据
  useEffect(() => {
    fetchData({});
  }, []);

  return (
    <div style={{ 
      padding: '20px',
      background: '#fff',
      minHeight: '100%',
      position: 'relative'
    }}>
      <Form
        form={form}
        layout="inline"
        style={{ 
          marginBottom: '16px',
          padding: '16px',
          background: '#f8f9fa',
          borderRadius: '4px'
        }}
      >
        <div style={{ display: 'flex', gap: '16px', flexWrap: 'wrap', width: '100%', justifyContent: 'space-between' }}>
          <div style={{ display: 'flex', gap: '16px', flexWrap: 'wrap' }}>
            <Form.Item name="shelfName" label="货架名称" style={{ marginBottom: '8px', minWidth: '200px' }}>
              <Input placeholder="请输入货架名称" allowClear />
            </Form.Item>
            <Form.Item name="shelfNumber" label="货架编号" style={{ marginBottom: '8px', minWidth: '200px' }}>
              <Input placeholder="请输入货架编号" allowClear />
            </Form.Item>
            <Form.Item style={{ marginBottom: '8px' }}>
              <Button type="primary" onClick={handleSearch} style={{ marginRight: '8px' }}>
                查询
              </Button>
              <Button onClick={handleReset}>
                重置
              </Button>
            </Form.Item>
          </div>
          <Form.Item style={{ marginBottom: '8px' }}>
            <Button type="primary" onClick={() => setIsAddModalOpen(true)}>
              新增货架
            </Button>
          </Form.Item>
        </div>
      </Form>

      <Table
        columns={columns}
        dataSource={Array.isArray(data) ? data : []}
        rowKey="id"
        loading={loading}
        size="middle"
        scroll={{ x: '100%', y: 'calc(100vh - 280px)' }}
        pagination={{
          current: currentPage,
          pageSize: pageSize,
          total: total,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `共 ${total} 条`,
          onChange: (page, size) => {
            setCurrentPage(page);
            setPageSize(size);
            fetchData(form.getFieldsValue());
          },
          onShowSizeChange: (current, size) => {
            setCurrentPage(1);
            setPageSize(size);
            fetchData(form.getFieldsValue());
          },
          pageSizeOptions: ['10', '20', '50', '100'],
        }}
      />

      <AddShelfManage
        open={isAddModalOpen}
        onCancel={() => setIsAddModalOpen(false)}
        onSuccess={() => {
          setIsAddModalOpen(false);
          fetchData({});
        }}
      />

      {currentShelf && (
        <EditShelfManage
          open={isEditModalOpen}
          onCancel={() => {
            setIsEditModalOpen(false);
            setCurrentShelf(null);
          }}
          onSuccess={() => {
            setIsEditModalOpen(false);
            setCurrentShelf(null);
            fetchData({});
          }}
          shelfData={currentShelf}
        />
      )}
    </div>
  );
};

export default ShelfManageQuery;
